#include "widget.h"
#include "ui_widget.h"

#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTextCodec>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_2_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    "选择CSV文件",
                                                    "C://Users//Mark//Desktop//Task.csv",
                                                    tr("CSV文件(*.csv)"));
    ui->lineEdit_2->setText(fileName);
}

void Widget::on_pushButton_clicked()
{
    // 获取文件路径
    QString fileName = ui->lineEdit_2->text();
    if (fileName.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择保存CSV文件的路径");
        return;
    }


    // 获取物料编号
    QString materialNo = ui->le_materialNo->text().trimmed();

    if(materialNo.isEmpty())
    {
        QMessageBox::warning(this, "警告", "物料编号不能为空");
        return;
    }

    // 获取工序编号
    QString workProcedureSequence = ui->le_workProcedureSequence->text().trimmed();

    if(workProcedureSequence.isEmpty())
    {
        QMessageBox::warning(this, "警告", "工序编号不能为空");
        return;
    }


    // 设置时间
    QDateTime dateTime;

    // 获取时间间隔
    int interval = ui->spinBox->value();
    QDateTime currentDateTime = QDateTime::currentDateTime();
    dateTime = currentDateTime.addSecs(interval); // 使用秒为单位的间隔

    ui->dateTimeEdit->setDateTime(dateTime);// 显示开始时间


    // 设置文件编码
#if 1
    // UTF-8
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    if (!codec) {
        QMessageBox::warning(this, "警告", "无法获取 UTF-8 编码");
        return;
    }
#else
    // GB18030
    QTextCodec *codec = QTextCodec::codecForName("GB18030");
    if (!codec) {
        QMessageBox::warning(this, "警告", "无法获取 GB18030 编码");
        return;
    }
#endif

    // 创建文件
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "警告", "无法创建文件");
        return;
    }

    QTextStream out(&file);
    out.setCodec(codec);

    // 写入 BOM（字节顺序标记）
//    out << QChar(0xFEFF);

// 写入头部
//        QString headerString = "产品代号,批次号,物料编号,物料名称,产品编号,产品码,工序序号,工序名称,拍照数量,开始时间\n";
        QString headerString = "物料编号,工序序号,开始时间\n";
        out << headerString;
// 写入数据行
//    out << QString("test_73bbf0e54def,test_b6580db168bd,%1,test_f4055cd6b57a,4231321,4123213231,%2,test_6745a935bd6b,3,%3\n")
        out << QString("%1,%2,%3\n")
           .arg(materialNo)
           .arg(workProcedureSequence)
           .arg(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
    // 刷新缓冲区
    out.flush();

    file.close();
}

